var server = require('../../utils/server');
var common = require('../../utils/common');
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    showPhonePop: false,
    showLoginPop: false,
    list: [],
    isEmpty: false,
    isLogin: true,
    isDisableLog: false,
    isDisableReg: false,
    isvip:0
  },
  onLoad(options) {
    this.data.isvip=options.isvip==undefined?0:options.isvip;
  },
  onShow() {
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.searchByStatus();
      },
      fail: res => {
        this.checkRegister();
      }
    })
  },
  checkRegister() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        if (JSON.stringify(res.data.member) == "{}") {
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            avatar: res.data.avatar
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {}
          })
          this.searchByStatus();
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showCheckTel() {
    wx.navigateTo({
      url: '../common/register',
    })
    this.setData({
      showPhonePop: false
    })
  },
  getPhoneNumber: function(e) {
    var that = this;
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code
          }, res => {
            if (res.data.errno == '0') {
              this.setData({
                isDisableReg: false
              })
              that.searchByStatus();
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isDisableLog: false
      })
      this.checkRegister();
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  searchByStatus() {
    common.showLoading();
    common.hideLoading();
    server.postJSON(common.storePath + 'coupon/couponloglist/', {
      "page": 1,
      "pageSize": 10,
      "status": 1,
      "is_vip":this.data.isvip
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          list: res.data.data,
          isEmpty: res.data.data.length > 0 ? false : true,
          isLogin: true
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  showHideDetail(e) {
    var index = e.currentTarget.dataset.index,
      nowToggle = this.data.list[index].toggle;
    this.setData({
      ['list[' + index + '].toggle']: !nowToggle
    })
  },
  goToGoodsList(e) {
    var eventid = e.currentTarget.dataset.eventid,
      goodsid = e.currentTarget.dataset.goodsid,
      eventgoodsid = e.currentTarget.dataset.eventgoodsid,
      eventtemplateid = e.currentTarget.dataset.eventtemplateid,
      isFullExchange = e.currentTarget.dataset.isfullchange,
      isVip = e.currentTarget.dataset.isvip,
      index = e.currentTarget.dataset.index;
      if(isVip=='1'){
        wx.navigateTo({
          url: '../../membership_supply/pages/productListsM4'
        })
      }else{
        if (eventid > 0) {
          if (eventtemplateid != '0') {
            wx.navigateTo({
              url: '../../membership_supply/pages/productListsM' + eventtemplateid + '?eventid=' + eventid
            })
          } else {
            wx.navigateTo({
              url: '../../membership_supply/pages/productDetailM?eventid=' + eventid + '&&goodsid=' + eventgoodsid
            })
          }
        } else {
          if (isFullExchange == '1' && goodsid!=''){
            wx.getStorage({
              key: 'storeId',
              success: resp => {
                console.log(resp)
                  this.setData({
                    ['list[' + index + '].isCanAdd']: true
                  })
                server.postJSON(common.storePath + 'cart/addgoods/', {
                  "store_id": resp.data,
                  "goods_id": goodsid,
                  "trace_id": '',
                  "scene": ''
                }, res => {
                  if (res.data.errno == "0") {
                    common.showErrorToast("添加成功");
                    this.setData({
                      ['list[' + index + '].isCanAdd']: false
                    })
                    app.globalData.cartIndexType=2;
                    wx.navigateTo({
                      url: '../cart/cartIndexSec',
                    })
                  } else {
                    this.setData({
                      ['list[' + index + '].isCanAdd']: false
                    })
                    common.showErrorToast(res.data.errmsg);
                  }
                })
              },
              fail: res => {
                wx.switchTab({
                  url: '../index/index',
                })
              }
            })
          }else{
            wx.switchTab({
              url: '../index/index',
            })
          }
         
        }
      }

  },
  //滚动到底部触发事件  
  onReachBottom() {
    console.log(this.data.page)
    let that = this;
    if (that.data.list.length > 4) {
      common.showLoading();
      common.hideLoading();
      that.data.page+=1;
      that.getMoreData()
    }
  },
  getMoreData() {
    server.postJSON(common.storePath + 'coupon/couponloglist/', {
      "page": this.data.page,
      "pageSize": 10,
      "status": 1,
      "is_vip":this.data.isvip
    }, res => {
      console.log(res)
      if (res.data.errno == "0") {
        common.hideLoading();
        if (res.data.data.length > 0) {
          console.log(res.data.data)
          var newData = this.data.list;
          newData = newData.concat(res.data.data)
          this.setData({
            list: newData,
            isEmpty: res.data.data.length > 0 ? false : true
          })
        }
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  toInvalidTickets() {
    wx.navigateTo({
      url: 'invalidVouchers?isvip='+this.data.isvip,
    })
  },
  goToCredit() {
    wx.navigateTo({
      url: 'creditShop',
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isLogin: false
    })
  },
  showLoginPop() {
    common.checkLogin().then(res => {
      if (res.errno == "0") {
        wx.setStorage({
          key: "sso",
          data: res.data.sso,
          success: res => {
            app.globalData.isGetWxUserinfo = true;
          }
        })
        if (JSON.stringify(res.data.member) == "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            showPhonePop: true
          })
        } else if (JSON.stringify(res.data.member) != "{}") {
          app.globalData.openid = res.data.openid;
          this.setData({
            tel: res.data.member.cellphone,
            ticketsnum: res.data.coupon_num,
            avatar: res.data.avatar
          })
          this.setData({
            showPhonePop: false,
            showLoginPop: false,
            isLogin: true
          })
          this.searchByStatus();
          this.getScoreCardNum(res.data.member.cellphone);
          this.storageUserinfo(res.data)
        }
      } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
        this.setData({
          showLoginPop: true
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  }
})